package com.xrit.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xrit.constant.MessageConstant;
import com.xrit.exception.CustomException;
import com.xrit.mapper.CheckGroupMapper;
import com.xrit.pojo.CheckGroup;
import com.xrit.query.QueryPageBean;
import com.xrit.result.PageResult;
import com.xrit.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    /**
     * 检查组列表
     * @return
     */
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.selectByExample(null);
    }

    /**
     * 添加检查组
     * @param group  检查组的基本信息
     * @param itemIds 检查项的ids
     */
    @Transactional
    @Override
    public void add(CheckGroup group, Integer[] itemIds) {
        checkGroupMapper.insertSelective(group);
        //第三方表
        if (itemIds!=null && itemIds.length>0){
            for (Integer id: itemIds) {
                //一条条的添加检查组和检查项的数据
                checkGroupMapper.addCheckGroupAndCheckItem(group.getId(),id);
            }
        }
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    @Override
    public void deleteById(Integer id) throws CustomException {
        //判断检查组是否被套餐使用了
        Integer count = checkGroupMapper.isUseInSetMeal(id);
        if (count>0){
            //被使用了则不能删除,手动抛出异常
            throw new CustomException(MessageConstant.CHECKGROUP_IN_USE);
        }
        //没被使用？
        //解除检查组和检查项之间的关系
        checkGroupMapper.deleteCheckGroupAndCheckItemByGroupId(id);
        checkGroupMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),true);
        // 有查询条件的处理, 模糊查询
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            // 拼接%
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString()+ "%");
        }
        Page<CheckGroup> page=checkGroupMapper.selectByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }
}
